package com.heima.wemedia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.stream.StreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.dtos.PageResponseResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.utils.WmThreadLocalUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Override
    public PageResponseResult<List<WmNews>> findList(WmNewsPageReqDto dto) {
        IPage<WmNews> page = this.page(new Page<>(dto.getPage(), dto.getSize()), Wrappers.<WmNews>lambdaQuery()
                .eq(ObjectUtil.isNotEmpty(dto.getStatus()), WmNews::getStatus, dto.getStatus())
                .eq(ObjectUtil.isNotEmpty(dto.getChannelId()), WmNews::getChannelId, dto.getChannelId())
                .like(ObjectUtil.isNotEmpty(dto.getKeyword()), WmNews::getTitle, dto.getKeyword())
                .between(ObjectUtil.isNotEmpty(dto.getBeginPubDate()) && ObjectUtil.isNotEmpty(dto.getEndPubDate()), WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate()));
        return PageResponseResult.<List<WmNews>>builder()
                .data(page.getRecords())
                .size(Convert.toInt(page.getSize()))
                .total(Convert.toInt(page.getTotal()))
                .currentPage(Convert.toInt(page.getPages()))
                .build();
    }

    @Override
    @Transactional
    public ResponseResult<Object> submitNews(WmNewsDto dto) {


        WmNews wmNews = BeanUtil.toBean(dto, WmNews.class);
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        List<String> images = dto.getImages();
        //如果文章封面类型为自动则进行处理
        if (ObjectUtil.equal(dto.getType(), WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            this.setAutoImages(wmNews);
        }
        //获取Content中的图片id并存入数据库
        this.addMaterialImage(wmNews, images);
        if (ObjectUtil.isEmpty(this.getOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, dto.getId())))) {
            //新增
            this.save(wmNews);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //修改
        this.update(wmNews, Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, dto.getId()));
        //删除素材库中关联图片
        this.removeMaterialImage(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult<WmNews> findOne(Integer id) {
        WmNews byId = this.getById(id);
        if (ObjectUtil.isEmpty(byId)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.okResult(byId);
    }

    @Override
    public ResponseResult<Object> delNews(Integer id) {
        try {
            WmNews byId = this.getById(id);
            if (ObjectUtil.isEmpty(byId)) {
                return ResponseResult.errorResult(1002, "文章不存在");
            }
            if (ObjectUtil.isEmpty(byId.getId())) {
                return ResponseResult.errorResult(501, "文章Id不可缺少");
            }
            if (ObjectUtil.equals(byId.getStatus(), WemediaConstants.WM_NEWS_SUBMIT)){
                return ResponseResult.errorResult(501, "文章已发布,不能删除");
            }
            this.remove(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, id));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            return ResponseResult.errorResult(501, "文件删除失败");
        }
    }

    @Override
    public ResponseResult<Object> downOrUp(WmNewsDto dto) {
        try {
            WmNews wmNews = this.getById(dto.getId());
            if (ObjectUtil.isEmpty(wmNews)) {
                return ResponseResult.errorResult(1002, "文章不存在");
            }
            if (ObjectUtil.isEmpty(wmNews.getId())) {
                return ResponseResult.errorResult(501, "文章Id不可缺少");
            }
            if (ObjectUtil.notEqual(wmNews.getStatus(), WemediaConstants.WM_NEWS_SUBMIT)){
                return ResponseResult.errorResult(501, "文章不是发布状态,不能上下架");
            }
            if (ObjectUtil.equal(dto.getEnable(), Convert.toShort(0))||ObjectUtil.equal(dto.getEnable(), Convert.toShort(1))) {
                wmNews.setEnable(Convert.toShort(dto.getEnable()));
            }else {
                return ResponseResult.errorResult(501, "参数错误,enable应该为0或1");
            }
            dto.setArticleId(wmNews.getArticleId());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSONUtil.toJsonStr(dto));
            this.update(wmNews, Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, dto.getId()));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            return ResponseResult.errorResult(501, "文件更改失败");
        }
    }


    private void setAutoImages(WmNews wmNews) {
        List<String> list = getList(wmNews);
        switch (list.size()) {
            case 0:
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
                break;
            case 1:
            case 2:
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                wmNews.setImages(CollUtil.getFirst(list));
                break;
            default:
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                ListUtil.sub(list, 0, 3).forEach(wmNews::setImages);
                break;
        }
    }

    private void addMaterialImage(WmNews wmNews, List<String> images) {
        //将dto中String类型的content转化为list
        List<String> collect = getList(wmNews);
        List<Integer> bodyIds = new ArrayList<>();
        List<Integer> titleIds = new ArrayList<>();
        for (String s : collect) {
            bodyIds.add(wmMaterialMapper.selectOne(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getUrl, s)).getId());
        }
        for (String image : images) {
            titleIds.add(wmMaterialMapper.selectOne(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getUrl, image)).getId());
        }
        if (ObjectUtil.isNotEmpty(bodyIds)) {
            wmNewsMaterialMapper.saveRelations(bodyIds, wmNews.getId(), Convert.toShort(0));
        }
        if (ObjectUtil.isNotEmpty(titleIds)) {
            wmNewsMaterialMapper.saveRelations(titleIds, wmNews.getId(), Convert.toShort(1));
        }
    }

    @NotNull
    private static List<String> getList(WmNews dto) {
        return StreamUtil.of(JSONUtil.toList(dto.getContent(), JSONObject.class))
                .filter(jsonObject -> StrUtil.equals(jsonObject.getStr("type"), "image"))
                .map(jsonObject -> jsonObject.getStr("value"))
                .collect(Collectors.toList());
    }

    private void removeMaterialImage(WmNews wmnews) {
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmnews.getId()));
    }
}

